/**
 * 弹框提示 函数
*/
function elasticFrame(text, callback){
    var d = document,
        body = d.body,
        cFrame = d.createElement('div');

    cFrame.className = 'elastic-frame';

    cFrame.innerHTML = `
                    <div class="ela-mask"></div>
                    <div class="ela-tips">
                        <div class="ela-tips-title">提示<div class="elastic-frame-close"><!--<span class="iconfont icon-guanbi"></span>--></div></div>
                        <div class="ela-tips-main flag">
                            <div class="ela-tips-con">${text}</div>
                            <div class="ela-confirm">确认</div>
                        </div>
                    </div>
                    `;
    var close = cFrame.querySelector('.elastic-frame-close'),
        confirm = cFrame.querySelector('.ela-confirm'),
        tips = cFrame.querySelector('.ela-tips'),
        mask = cFrame.querySelector('.ela-mask');
    close.addEventListener('click', function(){
        // 关闭
        animate();
    });

    confirm.addEventListener('click', function(){
        // 关闭前的回调
        callback && callback();
        // 关闭
        animate();
    });
    /*
     * 关闭动画
    */
    function animate(){
        tips.classList.add('ela-tips-js');
        mask.classList.add('ela-mask-js');
        var timer = setTimeout(function(){
            body.removeChild(cFrame);
            clearTimeout(timer);
        }, 300);
    }

    body.appendChild(cFrame);
    
}




/**
 * 加载动画
 * @param {number} transparent 背景层透明度0-1
*/
function addLoad(transparent){
    var d = document,
        oBody = d.body,
        fragment = d.createDocumentFragment(),
        oLoadBody = d.createElement('div'),
        oLoadItem = d.createElement('div'),
        // 背景层
        mask = d.createElement('div');
    oLoadBody.className = 'load-body';
    oLoadItem.className = 'load-item';
    mask.className = 'load-mask';
    if(transparent){
        mask.style.backgroundColor = "rgba(0,0,0, "+ transparent +")";
    }
    
    for(var i=1; i<=5; i++){
        var oDiv = d.createElement('div');
        oDiv.className = "rect rect"+i;
        oLoadItem.appendChild(oDiv);
    }
    oLoadBody.appendChild(mask);
    oLoadBody.appendChild(oLoadItem);
    fragment.appendChild(oLoadBody);
    oBody.appendChild(fragment);
}

/**
 * 关闭加载动画
*/
function remLoad(){
    var d = document,
        oBody = d.body,
        oLoadBody = d.querySelector('.load-body');
    if(!oLoadBody) return; 
    oBody.removeChild(oLoadBody);
}



/**
 * 添加body背景 函数
 *  @param {number} transparent 透明度0-1
 *  @param {function} fn 函数的参数是背景的dom节点
 *  
*/
function addBodyBg(transparent, fn){
    var oDiv = document.createElement('div');
    var setStyle = {
        background: `rgba(0,0,0, ${transparent})`,
        position: 'fixed',
        left: 0,
        top: 0,
        width: '100%',
        height: '100%',
        'z-index': 1000
      
    };
    var setAttr = {
        id: 'bodyBg',
        'data-bg': 'body-bg'
    };
    for(var attr in setAttr){
        oDiv.setAttribute(attr, setAttr[attr]);
    }
    for(var style in setStyle){
        oDiv.style[style] = setStyle[style];
    }
    var flag = document.querySelector('body').appendChild(oDiv);
    if(!flag){  
        console.error('添加dom节点失败');
    }
    if(fn){
        fn(oDiv);
    }
    
}

/**
 * 删除body背景 函数
*/
function remBodyBg(fn){
    var oDiv = document.querySelector('#bodyBg'),
        oBody = document.querySelector('body');

    if(oDiv && oDiv.getAttribute('data-bg')){
        //  删除body背景前的回调
        fn && fn();
        oBody.removeChild(oDiv);
    }else{
        console.error('该dom节点不存在');
    }
    
}


/**
 * 获取css属性值 
 * @param {object} curEle 要获取的dom对象
 * @param {string} attr 要获取的属性 
*/
function getCss(curEle,attr){  
    var val = null,reg = null;  
    if("getComputedStyle" in window){  
        val = window.getComputedStyle(curEle,null)[attr];  
    } else {   //ie6~8不支持上面属性  
        //不兼容  
        if(attr === "opacity"){  
            val = curEle.currentStyle["filter"];   //'alpha(opacity=12,345)'  
            reg = /^alphaopacity=(\d+(?:\.\d+)?)opacity=(\d+(?:\.\d+)?)$/i;  
            val = reg.test(val)?reg.exec(val)[1]/100:1;  
        } else {  
            val = curEle.currentStyle[attr];  
        }  
    }  
    reg = /^(-?\d+(\.\d)?)(px|pt|em|rem)?$/i;  
    return reg.test(val)?parseFloat(val):val;   
}


/**
 * 切换商品页面函数
 * @param {boolean} flag  true位打开商品列表界面, false为关闭商品列表界面
 * @param {object} option 要位移的节点
*/
function switchPageFn(flag, option){

    if(flag){
      
        //addPage(option);
        goodsListFn(option, function(node, bodyCon, goodsListHeader){
            node.classList.add('goods-list-module-js');
            bodyCon.style.overflowY = 'hidden';
            // 过度完成后改成fixed
            var timer = setTimeout(function(){
                goodsListHeader.style.position = 'fixed';
                clearTimeout(timer);
            }, 400);
        });
    }else{

        //remPage(option);
        goodsListFn(option, function(node, bodyCon, goodsListHeader){
            goodsListHeader.style.position = 'absolute';
            bodyCon.style.overflowY = 'scroll';
            node.classList.remove('goods-list-module-js');
        });
    }

    function goodsListFn(option, fn){
        var node = option.node,
            bodyCon = document.querySelector('.body-content'),
            goodsListHeader = document.querySelector('.goods-list-header');
        fn(node, bodyCon, goodsListHeader);
    }








    function addPage(option){
        var node = option.node;
        var bodyCon = document.querySelector('.body-content');
        var goodsListHeader = document.querySelector('.goods-list-header');

        node.classList.add('goods-list-module-js');
        bodyCon.style.overflowY = 'hidden';


        var timer = setTimeout(function(){
            goodsListHeader.style.position = 'fixed';
            clearTimeout(timer);
        }, 400);
    }



    function remPage(option){
        var node = option.node;
        var bodyCon = document.querySelector('.body-content');
        var goodsListHeader = document.querySelector('.goods-list-header');

        goodsListHeader.style.position = 'absolute';
        bodyCon.style.overflowY = 'scroll';
        node.classList.remove('goods-list-module-js');
    }
    
    
    

}

/**
 * 切换商品详情页面函数
 * @param {boolean} flag  true位打开商品列表界面, false为关闭商品列表界面
 * @param {object} option 要位移的节点
*/
function switchGoodsDetailsFn(flag, option){
    if(flag){
        switchGoodsDetails(option, function(node, className){
            node.classList.add(className);
        });
    }else{
        switchGoodsDetails(option, function(node, className){
            node.classList.remove(className);
        });
    }

    function switchGoodsDetails(option, fn){
        var node = option.node;
        var className = option.className;
        fn(node, className);
        
    }

}


/**
 * 移动端触摸左右滑动 函数
*/
function Getslide(option){
    // 要操作的dom节点
    this.node = option.elNode;
    // 视口宽度
    this.vw = option.vw;
    // 要移动的距离
    this.moveUp = option.moveUp;
    // 过度时间
    this.time = option.time;
    // ul起始位置
    this.lateStartX = option.lateStartX;
    // ul 结束位置
    this.lateEndX = option.lateEndX;
//console.log(this.lateStartX)
    // 获取html的font-size(转换成rem)
    this.fontSize = Number(getCss(document.querySelector("html"), 'font-size'));
    // 手指触摸位置
    this.startX;
    // 手指滑动位置
    this.moveX;
    // 手指抬起位置
    this.endX;
    //点击时获取当前ul的translateX
    this.lateX = option.lateStartX;
    // 手指点击的时间戳
    this.startTime; 
    // 手指抬起的时间戳
    this.endTime;
    // 防止滑动过快
    this.flag = true;

    this.autoX = option.lateStartX;
    // 初始化
    this.init();

    this.autoplay();
}
Getslide.prototype = {
    /**
     * 初始化
    */
    init: function(){
        var This = this;
        this.node.addEventListener('touchstart', this.start.bind(this));
        // this.node.addEventListener('touchstart', function(event){
        //     This.start(event);
        // });
    },
    /**
     * 触摸事件
    */
    start: function(event){
        var This = this;
        clearInterval(This.timer);
        // 防止滑动过快
        if(!This.flag) return;
        This.flag = false;
        
        //targetTouches 获取当前dom上的所有手指列表
        //this.startX = event.targetTouches[0].clientX; // 获取第一个
        var touch = event.targetTouches[0];
        This.startX = touch.clientX;
        This.lateX = This.translateX() / This.fontSize;

        This.startTime = new Date().getTime();
        
        //console.log(This.startTime)
        //console.log(this)
        this.moveBind = this.move.bind(this);
        this.endBind = this.end.bind(this);
        this.node.addEventListener('touchmove', this.moveBind);
        this.node.addEventListener('touchend', this.endBind);
        // this.node.addEventListener('touchmove', function(event){
        //     This.move(event)
        // });
        // this.node.addEventListener('touchend', function(event){
        //     This.end(event);
        // });
        //console.log(this.lateX)
    },
    /**
     * 滑动事件
    */
    move: function(event){
        var This = this;
        clearInterval(This.timer);
        //console.log(this)
        //可为阻止触摸时浏览器的缩放、滚动条滚动等
        event.preventDefault();
        //当屏幕有多个touch或者页面被缩放过，就不执行move操作
        if(event.targetTouches.length > 1 || event.scale && event.scale !== 1) return;
        
        var touch = event.targetTouches[0];
        This.moveX = touch.clientX;
        This.direction('move');
        //console.log(this)
        //console.log()
        //console.log(event.targetTouches)
    },
    /**
     * 手指抬起
    */
    end: function(event){
        //console.log(0)
        var This = this;
        //changedTouches涉及当前事件的触摸点的列表。
        var touch = event.changedTouches[0];
        This.endX = touch.clientX;
        This.endTime = new Date().getTime();
        
        This.direction('end');
        this.node.removeEventListener('touchmove', this.moveBind);
        this.node.removeEventListener('touchend', this.endBind);
        this.moveBind = null;
        this.endBind = null;
       
        // this.node.removeEventListener('touchmove', This.move);
        // this.node.removeEventListener('touchend', This.end);
        //console.log(this.moveX)
        // setTimeout(function(){
        //     console.log('niaho')
        // }, 1000);
        // 防止用户移动过快造成bug
        var timer = setTimeout(function(){
            This.flag = true;
            clearTimeout(timer);
        }, 400);
        This.autoplay();
    },
    /**
     * 方向判断
    */
    direction: function(type, fn){
        var This = this;
        // if(type == 'move'){
        //     var move = (This.moveX - This.startX) / This.fontSize;
        //     This.addDom('none', `translateX(${This.lateX + move}rem)`);
        // }
        // 未移动时不执行(没添加有点击bug)
        if(This.startX == This.endX) return;
        // 获取滑动的距离
        var move = (This.moveX - This.startX) / This.fontSize;
        if(move > 0){  // 向右移动
            if(type == 'move'){
                This.addDom('none', `translateX(${This.lateX + move}rem)`);
            }else if(type == 'end'){
                This.springback('right');
            }
        }else{ // 向左移动
            if(type == 'move'){
                This.addDom('none', `translateX(${This.lateX + move}rem)`);
            }else if(type == 'end'){
                This.springback('left');
            }
        }
    },
    /**
     * 滑动距离不够时(执行回弹) 反之执行(移动操作)
    */
    springback: function(type){
        var This = this;
        if(type == 'right'){
            
            var moveUp = This.lateX + This.moveUp / 100;
            // 判断滑动时间,以及距离
            if(This.endTime - This.startTime < 200 && This.moveX - This.startX > This.vw / 15){
                This.addDom(`transform ${This.time/1000}s`, `translateX(${moveUp}rem)`);
                // 防止自动轮播到第一张出bug
                if(Math.ceil(This.autoX) >= This.lateStartX){
                    This.autoX = This.lateEndX;   
                }else{
                    This.autoX = This.moveUp / 100 + This.autoX;
                }
                This.ulPosition('right');
                return;
            }
            // 判断滑动距离
            if(This.moveX - This.startX > This.vw / 2){// 执行移动操作
                This.addDom(`transform ${This.time/1000}s`, `translateX(${moveUp}rem)`);
                
                This.ulPosition('right'); 
            }else{ // 执行回弹操作
                This.addDom(`transform ${This.time/1000}s`, `translateX(${This.lateX}rem)`);
            }
        }else if(type == 'left'){
            var moveUp = -This.moveUp / 100 + This.lateX;
            // 判断滑动时间以及距离
            if(This.endTime - This.startTime < 200 && This.startX - This.moveX > This.vw / 15){
                This.addDom(`transform ${This.time/1000}s`, `translateX(${moveUp}rem)`);
           
                // 防止自动轮播到最后一张出bug
                if(Math.floor(This.autoX) <= This.lateEndX){
                    This.autoX = This.lateStartX;   
                }else{
                    This.autoX = -This.moveUp / 100 + This.autoX;
                }
                This.ulPosition('left');
                return;
            }
            //判断滑动距离
            if(This.startX - This.moveX > This.vw / 2){// 执行移动操作
                This.addDom(`transform ${This.time/1000}s`, `translateX(${moveUp}rem)`);
                // 防止自动轮播到最后一张出bug
                if(Math.floor(This.autoX) <= This.lateEndX){
                    This.autoX = This.lateStartX;   
                }else{
                    This.autoX = -This.moveUp / 100 + This.autoX;
                }
                This.ulPosition('left');
            }else{// 执行回弹操作
                This.addDom(`transform ${This.time/1000}s`, `translateX(${This.lateX}rem)`);
            }
        }
    },
    /**
     * 添加dom
     * @param {string} transitionValue 过度值
     * @param {string} translateXValue 位移值
    */
    addDom: function(transitionValue, translateXValue){
        var timer;
        //clearTimeout(timer);
        var This = this;
        This.node.style.transition = transitionValue;
        This.node.style.transform = translateXValue;
        // timer = setTimeout(function(){
        //     clearTimeout(timer);
        // }, This.time);
    },
    /**
     * ul重新定位(到达第一和最后时)
     */
    ulPosition: function(type){
        var This = this;
        if(type == 'right'){
            if(Math.ceil(This.lateX) >= This.lateStartX){
                var timer = setTimeout(function(){
                    This.addDom('none', `translateX(${This.lateEndX}rem)`);
                    //This.lateX = This.lateEndX;
                    clearTimeout(timer);
                }, This.time);
            }
        }else{
            if(Math.floor(This.lateX) <= This.lateEndX){
                var timer = setTimeout(function(){
                    This.addDom('none', `translateX(${This.lateStartX}rem)`);
                    //This.lateX = This.lateStartX;
                    clearTimeout(timer);
                }, This.time);
            }
        }
    },
    /**
     * 自动轮播
     */ 
    autoplay: function(){
        var This = this;
        This.timer = setInterval(function(){
            var moveUp = -This.moveUp / 100 + This.autoX;
            This.addDom(`transform ${This.time/1000}s`, `translateX(${moveUp}rem)`);
            // 最后一张时重新定位
            if(Math.floor(This.autoX) <= This.lateEndX){
                var timer = setTimeout(function(){
                    This.addDom('none', `translateX(${This.lateStartX}rem)`);
                    This.autoX = This.lateStartX;       
                }, This.time);
            }
            This.autoX = moveUp;
        }, 3000);
    },
    /**
     * 获取css的transform: translateX
     */
    translateX: function(){
        var node = this.node;
        var translateX = getCss(node, 'transform'),
            translateX = translateX.replace(/[^0-9-.,]/g, '').split(',');     
            return Number(translateX[translateX.length-2]);
    }

};


